from django.utils.deprecation import MiddlewareMixin
import time
from django.shortcuts import HttpResponse

VISIT_HISTORY = {
    # ip：[9:18:05,9:18:06]
    # ip：[9:18:06, 9:18:05,]
}


class Throttle(MiddlewareMixin):

    # def process_request(self, request):
    #     # 获取IP
    #     ip = request.META.get('REMOTE_ADDR')
    #     # 根据IP获取访问记录
    #     history = VISIT_HISTORY.get(ip, [])
    #
    #     now = time.time()
    #     for i in history[:]:
    #         if now - i >= 5:
    #             history.remove(i)
    #
    #
    #     if len(history) >= 3:
    #         return HttpResponse('你的频率太快了，需要歇一会')
    #
    #     history.append(now)
    #     VISIT_HISTORY[ip] = history

    # def process_request(self, request):
    #     # 获取IP
    #     ip = request.META.get('REMOTE_ADDR')
    #     # 根据IP获取访问记录
    #     history = VISIT_HISTORY.get(ip, [])
    #
    #     now = time.time()
    #
    #     while history and now - history[-1] > 5:
    #         history.pop()
    #
    #     if len(history) >= 3:
    #         return HttpResponse('你的频率太快了，需要歇一会')
    #
    #     history.insert(0, now)
    #     VISIT_HISTORY[ip] = history

    def process_request(self, request):

        history = request.session.get('history', [])

        now = time.time()

        while history and now - history[-1] > 5:
            history.pop()

        if len(history) >= 3:
            return HttpResponse('你的频率太快了，需要歇一会')

        history.insert(0, now)
        request.session['history'] = history
